jQuery(function($){
	(function($stockInfo, item_size){
		if ($stockInfo.length <= 0) return;

		function generate_stock_info(sku) {
			return sku.stockText;
		}

		if (item_size <= 0) {//SINGLE
			$("#packageStatus").addClass($('select[name=product_item_id]').find("option:selected").data('stock-status'));
			$('select[name=product_item_id]').on('change', function() {
				var $sku = $(this.options[this.selectedIndex]);
				$stockInfo.html(generate_stock_info($sku.data()));
				$("#packageStatus").removeClass().addClass($sku.data('stock-status'));
			});
		} else {//SET
			var $all_item = $('[name="product_item_id[]"]');
			function updateDispDate() {
				var max_time = 0,
					last_status = null,
					$max_item = null;
				$all_item.each(function() {
					var $item, stock_time, stock_status;
					if (this.type === 'hidden') {
						$item = $(this);
					} else {
						$item = $(this.options[this.selectedIndex]);
					}
					stock_time = $item.data('stock-time');
					stock_status = $item.data('stock-status');
					if (max_time <= stock_time) {
						max_time = stock_time;
						last_status	= stock_status;
						$max_item = $item;
					}
				});
				if (!$max_item) {
					$max_item = $all_item.find('[data-stock-status=in_stock]:first-child');
				}
				$stockInfo.html(generate_stock_info($max_item.data()));
				$("#packageStatus").removeClass().addClass(last_status);
			}
			$all_item.filter('select').on('change', updateDispDate);
			updateDispDate();
		}
	}($('.stock_info'), $('[name="item_quantity[]"]').length));

	(function(area){
		if(area.length <= 0){
			return;
		};
		var	className = {
				btnSku_defalut : "_btnSku_defalut",
				btnTxtWidth : "_btnTxtWidth",
				btnTxtHeight : "_btnTxtHeight",
				switchSelect : "_switchSelect",
				onAxisSelect : "_onAxisSelect",
				onSkuSelect : "_onSkuSelect",
				onNotDeliveryOnlySelect : "_onNotDeliveryOnlySelect",
				titleTxtModalSkuSelect : "_titleTxtModalSkuSelect",
				axisSelect : "_axisSelect",
				axisItem : "_axisItem",
				skuSelect : "_skuSelect",
				skuItem : "_skuItem",
				skuItemNotDeliveryQuick : "_skuItemNotDeliveryQuick",
				skuItemDeliveryQuickText : "_skuItemDeliveryQuickText",
				skuItemAxisTitle : "_skuItemAxisTitle",
				skuItemRadio : "_skuItemRadio",
				backAxisSelect : "_backAxisSelect",
				closeSkuSelectModal : "_closeSkuSelectModal",
				skuSelectModal : "_skuSelectModal",
				stockInfoWrap : "_stockInfoWrap",
				modalCloseScrollTop : "_modalCloseScrollTop",
				unselect : "_unselect",
				selected : "_selected",
				checked : "_checked",
				btnUndecide : "_btnUndecide",
				skuCartButton : "_skuCartButton"
		};
		var	nodeIndex = {
				area : area,
				btnSku_defalut : area.find("."+className.btnSku_defalut),
				btnTxtWidth : area.find("."+className.btnTxtWidth),
				btnTxtHeight : area.find("."+className.btnTxtHeight),
				switchSelect : area.find("."+className.switchSelect),
				axisSelect : area.find("."+className.axisSelect),
				axisItem : area.find("."+className.axisItem),
				titleTxtModalSkuSelect : area.find("."+className.titleTxtModalSkuSelect),
				skuSelect : area.find("."+className.skuSelect),
				skuItem : area.find("."+className.skuItem),
				skuItemNotDeliveryQuick : area.find("."+className.skuItemNotDeliveryQuick),
				skuItemDeliveryQuickText : area.find("."+className.skuItemDeliveryQuickText),
				skuItemAxisTitle : area.find("."+className.skuItemAxisTitle),
				skuItemRadio : area.find("."+className.skuItemRadio),
				backAxisSelect : area.find("."+className.backAxisSelect),
				closeSkuSelectModal : area.find("."+className.closeSkuSelectModal),
				skuSelectModal : area.find("."+className.skuSelectModal),
				stockInfoWrap : area.find("."+className.stockInfoWrap),
				btnUndecide : area.find("."+className.btnUndecide),
				modalCloseScrollTop : area.find("."+className.modalCloseScrollTop),
				skuCartButton : area.find("."+className.skuCartButton)
		};

		/* 未選択時 */
		if(nodeIndex.stockInfoWrap.hasClass(className.btnUndecide)){
			var s = $("#packageStatus").find("input[type='submit']"),
				p = s.prev("a");
			p.removeClass("_submit").attr("href","#sku_modal").attr("rel","sku_Modal");
			$(".reservation_n_note",".in_stock_n_note",".reservation_n_btn",".normal_maker_order_n_btn",".in_stock_n_btn").hide();
		};

		function close_sku_modal(sku_modal_id){
			var top = $(sku_modal).data("scroll-top");
			setTimeout(function(){
				$(sku_modal_id).fadeOut(0);
				setTimeout(function(){
					$("body").animate({scrollTop:top},0);
					setTimeout(function(){
						$("#skuLeanOverlay").fadeOut(400);
						setTimeout(function(){
							$("#skuLeanOverlay").remove();
						},200);
					},0);
				},0);
			},0);
		};

		function modal_scroll_top(sku_modal_id){
			var scrT = window.pageYOffset,
				windowHeight = (!(window.innerHeight)) ? document.documentElement.clientHeight : window.innerHeight,
				ch = ((windowHeight - $(sku_modal_id).height())/2) + scrT;
			if(ch < 0){
				ch = 10 + scrT;
			}else if(windowHeight < $(sku_modal_id).height()){
				ch = 10 + scrT;
			}
			var ch = 60 + scrT;
			$(sku_modal_id).css({
				"top":ch
			});
		};

		$("a[rel*=sku_Modal]").each(function(){
			var $sku_modal_id = $("#sku_modal");
			$(this).on("click",function(e){
				if($(this).prop("rel") != "sku_Modal") return;
				e.preventDefault();
				$("body").append("<div id='skuLeanOverlay'></div>");
				$("#skuLeanOverlay").on("click",function(e){
					e.preventDefault();
					close_sku_modal("#sku_modal");
					var top = $sku_modal_id.data("scroll-top");
					setTimeout(function(){
						$sku_modal_id.css({"display":"none"});
						setTimeout(function(){
							$("body").animate({scrollTop:top},0);
						},0);
					},0);
				});
				var scrT = window.pageYOffset,
					windowHeight = (!(window.innerHeight)) ? document.documentElement.clientHeight : window.innerHeight,
					ch = ((windowHeight - $sku_modal_id.height())/2) + scrT;
				if(ch < 0){
					ch = 10 + scrT;
				}else if(windowHeight < $sku_modal_id.height()){
					ch = 10 + scrT;
				}
				ch = 60 + scrT;

				$("#skuLeanOverlay").css({"display":"block",opacity:0}).fadeTo(200,0.9);
				$sku_modal_id.data("scroll-top");
				$sku_modal_id.attr("data-scroll-top",$("body").scrollTop());
				$sku_modal_id.data("scroll-top",$("body").scrollTop());
				$sku_modal_id.data("scroll-top");
				$sku_modal_id.css({"display":"block","position":"absolute","opacity":0,"z-index":11000,"top":ch,"left":"3%"}).fadeTo(200, 1);
				$sku_modal_id.attr("data-modal-scroll-top",ch)
			});
		});

		nodeIndex.axisItem.each(function(){
			var self = $(this);
			self.on('click',function(e){
				e.preventDefault();
				nodeIndex.axisItem.removeClass(className.selected);
				self.addClass(className.selected);
				var axis = $(this),
					axistype = axis.data("axis-type"),
					axisno = axis.data("axis-no"),
					axisname = axis.data("axis-name");
				/* axis決定時処理 */
				setTimeout(function(){
					checkedsku = nodeIndex.skuSelect.find($("._checked"));
					checkedskuno = checkedsku.data("axis-width-no");
					nodeIndex.axisSelect.hide();
					nodeIndex.backAxisSelect.show();
					if(axistype == "delivery_quick"){
						nodeIndex.titleTxtModalSkuSelect.html("<span class='titleTxtModalSkuSelect_axis'>" + axisname + "</span>を選択してください");
					}else{
						nodeIndex.titleTxtModalSkuSelect.html("現在<span class='titleTxtModalSkuSelect_axis'>" + axisname + "</span>を選択しています");
						nodeIndex.switchSelect.addClass(className.onNotDeliveryOnlySelect)
					}
					nodeIndex.skuSelect.fadeIn();
					modal_scroll_top("#sku_modal");
					nodeIndex.skuItem.each(function(){
						var sku = $(this),
							skuRadio = sku.find($("input:radio[name='product_item_id']"));
							axisWidthNo = sku.data("axis-width-no"),
							axisHeightNo = sku.data("axis-height-no");
						sku.show();
						if(axistype == "delivery_quick"){
							if(sku.hasClass(className.skuItemNotDeliveryQuick)){
								sku.hide();
								nodeIndex.skuItemDeliveryQuickText.hide();
							};
						}else if(axistype == "width"){
							if(axisWidthNo != axisno){
								sku.hide();
							};
						}else if(axistype == "height"){
							if(axisHeightNo != axisno){
								sku.hide();
							}else if(checkedskuno == axisWidthNo){
								var checkedSkuItem = $(this).closest(nodeIndex.skuItem);
								sku.find($("input:radio[name='product_item_id']")).attr("checked","checked");
								nodeIndex.btnTxtWidth.html(skuRadio.data("axis-width-name"));
								nodeIndex.btnTxtHeight.html(skuRadio.data("axis-height-name"));
								$(".stock_info").html(skuRadio.data('stock-text'));
								$("#packageStatus").removeClass().addClass(skuRadio.data('stock-status'));
								nodeIndex.btnSku_defalut.hide();
								nodeIndex.skuItem.removeClass(className.checked);
								sku.addClass(className.checked);
								nodeIndex.skuItem.find(nodeIndex.skuCartButton).hide();
								checkedSkuItem.addClass(className.checked);
								checkedSkuItem.find(nodeIndex.skuCartButton).fadeIn();
								setTimeout(function(){
									var s = $("#packageStatus").find("input[type='submit']"),
										p = s.prev("a");
									p.addClass("_submit").attr("href","#").attr("rel","");
									nodeIndex.stockInfoWrap.show().removeClass(className.btnUndecide);
								},400);
							};
						};
					});
				},200);
			});
		});
		/* 戻る処理 */
		nodeIndex.backAxisSelect.on('click',function(e){
			e.preventDefault();
			var back = $(this),
				s = $("#packageStatus").find("input[type='submit']"),
				p = s.prev("a"),
				title = nodeIndex.titleTxtModalSkuSelect.data("title-axis-name");
			setTimeout(function(){
				p.removeClass("_submit").attr("href","#sku_modal").attr("rel","sku_Modal");
				nodeIndex.skuSelect.hide();
				nodeIndex.axisSelect.fadeIn();
				nodeIndex.titleTxtModalSkuSelect.html(title + "選択してください");
				nodeIndex.switchSelect.removeClass(className.onNotDeliveryOnlySelect).removeClass(className.onSkuSelect).addClass(className.AxisSelect);
				nodeIndex.btnTxtWidth.html("");
				nodeIndex.btnTxtHeight.html("");
				nodeIndex.btnSku_defalut.show();
				nodeIndex.skuItemDeliveryQuickText.show();
				nodeIndex.skuSelect.attr("data-checked-width-no",($("input:radio[name='product_item_id']:checked").closest(nodeIndex.skuItem).data('axis-width-no')));
				nodeIndex.skuSelect.attr("data-checked-height-no",($("input:radio[name='product_item_id']:checked").closest(nodeIndex.skuItem).data('axis-height-no')));
				back.fadeOut();
				modal_scroll_top("#sku_modal");
				setTimeout(function(){
					nodeIndex.stockInfoWrap.addClass(className.btnUndecide).hide();
					$("input:radio[name='product_item_id']").attr("checked",false);
				},100);
			},100);
		});
		/* sku決定時処理 */
		$("input:radio[name='product_item_id']").on('change',function(){
			var checkedRadio = $("input:radio[name='product_item_id']:checked"),
				checkedSkuItem = checkedRadio.closest(nodeIndex.skuItem);
			nodeIndex.btnTxtWidth.html(checkedRadio.data('axis-width-name'));
			nodeIndex.btnTxtHeight.html(checkedRadio.data('axis-height-name'));
			$(".stock_info").html(checkedRadio.data('stock-text'));
			$("#packageStatus").removeClass().addClass(checkedRadio.data('stock-status'));
			nodeIndex.btnSku_defalut.hide();
			nodeIndex.skuItem.removeClass(className.checked);
			if(nodeIndex.stockInfoWrap.hasClass(className.btnUndecide)){
				nodeIndex.stockInfoWrap.show().removeClass(className.btnUndecide);
				var s = $("#packageStatus").find("input[type='submit']"),
				p = s.prev("a");
				p.addClass("_submit").attr("href","#").attr("rel","");
			};
			nodeIndex.skuItem.find(nodeIndex.skuCartButton).hide();
			checkedSkuItem.addClass(className.checked);
			checkedSkuItem.find(nodeIndex.skuCartButton).fadeIn();
		});
		/* 閉じる処理 */
		nodeIndex.closeSkuSelectModal.on('click',function(){
			close_sku_modal("#sku_modal");
		});
	})($('#skuSelect'));

	$.fn._shopToggle = function(){
		var shopToggleTrigger = $('._shopToggleTrigger');
		shopToggleTrigger.each(function(){
			var self				= $(this),
				shopToggleContents	= self.parent('._shopToggleContents'),
				shopToggleTarget	= self.next('._shopToggleTarget');
			self.on('click', function(e){
				e.preventDefault();
				if(shopToggleContents.hasClass('_on')){
					self.next(shopToggleTarget).slideUp();
					shopToggleContents.removeClass('_on');
				}else{
					self.next(shopToggleTarget).slideDown();
					shopToggleContents.addClass('_on');
				}
			});
		});
	};

	$.fn._shopToggle = function(){	
		$("._shopToggleSwich").each(function(){
			var switcher = $(this);
			switcher.on("click",function(e){
				e.preventDefault();
				if(switcher.hasClass("_shopToggleSwichOff")){
					switcher.closest($("._shopToggleSwichItem")).find($("._shopToggleSwichContents")).slideDown("fast");
					switcher.removeClass("_shopToggleSwichOff").addClass("_shopToggleSwichOn");
					switcher.find("._shopToggleSwich_text").text("閉じる");
				}else{
					switcher.closest($("._shopToggleSwichItem")).find($("._shopToggleSwichContents")).slideUp("fast");
					switcher.removeClass("_shopToggleSwichOn").addClass("_shopToggleSwichOff");	
					switcher.find("._shopToggleSwich_text").text("詳細を見る");	
				};
			});
		});
	};
});
$(function(){
    $('body')._shopToggle();

	$("#_addFavBtn").on("click",function(e){
		e.preventDefault();
		$.ajax({
			type: "GET",
			url: $(this).prop("href"),
			dataType:'json',
			success: function(d){
				var resultTxt = "";
				if(d.status == "OK"){
					resultTxt = "お気に入りアイテムに追加しました"
				}else{
					resultTxt = "通信に失敗しました"
				}
				$.oneLineTxt(resultTxt);
			}
		});
	});


});
$('#close,.close_window').click(function (){
    window.close();
    return false;
});
jQuery(function($) {
    function isNeedTwoLines(target){
        var $t = $(target),
            $c = $t.clone(),
             r = false;
        $c
            .css({
                display: 'none',
                position : 'absolute',
                overflow : 'visible'
            })
            .width($t.width())
            .height('auto');

        // DOMを一旦追加
        $t.after($c);
        if($c.height() > $t.height()){
            r = true;
        }
        $c.remove();
        return r;
    }
    function multiLineEllipsis(target, add){
        var $t = $(target),
            $c = $t.clone(),
             h = $t.html(),
             r = false;
        $c
            .css({
                display: 'none',
                position : 'absolute',
                overflow : 'visible'
            })
            .width($t.width())
            .height('auto');

        // DOMを一旦追加
        $t.after($c);

        // 指定した高さになるまで、1文字ずつ消去していく
        while((h.length > 0) && ($c.height() > $t.height())) {
            h = h.substr(0, h.length - 1);
            $c.html(h + add);
            r = true;
        }
        if(r){
            // 高さ調整したのに...で終わっていない場合は改行が末尾にあって適用されなかったため...を付加
            var res = $c.html();
            if (res.substring(res.length-5,res.length-1) == '<br>'){
                res = res.substring(0,res.length-5);
            }
            if (res.substring(res.length-4,res.length-1) != '...'){
                res = res + '...';
            }
            $c.html(res);
        }
        // 文章を入れ替えて、複製した要素を削除する
        $t.html($c.html());
        $c.remove();
        return r;
    }
    $('._textAdjustHeight').each(function() {
        var $target = $(this);
        var html = $target.html();// オリジナルの文章を取得する
        // 高さ調整必要なら2行タイプのスタイル適用
        if(isNeedTwoLines($target)){
            $target.addClass('double_line pr');
            $target.children('.arrow').addClass('db');
            $target.prev('dt').addClass('double_line');
        }
        if(multiLineEllipsis($target, '...<span class="arrow"></span>')){
            $target.find('.dd_inner').css('pointer-events', 'inherit');
        }
    });
    $("a[rel*=leanModal]").leanModal({
        top : 10,
        overlay : 0.9,
        closeButton : ".modal_list_close"
    });
    $('._textAdjustReview').each(function() {
        var $target = $(this);
        var html = $target.html();
        if(isNeedTwoLines($target)){
            $target.addClass('double_line');
        }
        multiLineEllipsis($target, '...');
    });
    $("._shopToggleSwichOff").on("click",function(){
        $('._textAdjustHeight').each(function() {
            var $target = $(this);
            var html = $target.html();// オリジナルの文章を取得する
            // 高さ調整必要なら2行タイプのスタイル適用
            if(isNeedTwoLines($target)){
                $target.addClass('double_line pr');
                $target.children('.arrow').addClass('db');
                $target.prev('dt').addClass('double_line');
            }
            if(multiLineEllipsis($target, '...<span class="arrow"></span>')){
                $target.find('.dd_inner').css('pointer-events', 'inherit');
            }
        });
        $("a[rel*=leanModal]").leanModal({
            top : 10,
            overlay : 0.9,
            closeButton : ".modal_list_close"
        });
    });

    $('._clickableArea').click(function() {
        $(this).closest('._setToggleSwich').toggleClass('_open');// arrow向き変更&height:autoスタイル適用
        $(this).closest('._setToggleSwich').find('._toggleHide').toggle();
    });
});

//数量
function minus() {
	var a = parseInt($("#number").val(), 10);
	if (a <= 1) {
		$("#number").val(1);
	} else {
		a--;
		$("#number").val(a);
	}
}

function plus() {
	var a = parseInt($("#number").val(), 10);
	if (a >= 999) {
		$("#number").val(1);
	} else {
		a++;
		$("#number").val(a);
	}
}

function modify() {
	var a = parseInt($("#number").val(), 10);
	if ("" == $("#number").val()) {
		$("#number").val(1);
		return
	}
	if (!isNaN(a)) {
		if (1 > a || a > 999) {
			$("#number").val(1);
			return
		} else {
			$("#number").val(a);
			return
		}
	} else {
		$("#number").val(1);
	}
}
